<script setup lang="ts">
import { reactive, ref } from "vue";
import {ElMessage, ElMessageBox, type UploadProps} from "element-plus";
import request from "@/utils/request.ts";
import axios from 'axios'
const formRef = ref();
const data = reactive({
  userid: null,
  username: null,
  password: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  formVisible: false,
  formTitle:null,
  form: {
    userid:'',
    username: '',
    password: '',
    phone: '',
    vip: '',
    role:'',
    avatar: '',
  },
  rows:[],//多选按钮点击时信息存储
  user : JSON.parse(localStorage.getItem('code_user')||"{}"),
})
const load = () => {
  request.get('/user', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      username: data.username,
      userid: data.userid
    }
  }).then(res => {
    if (res.status == 200) {
      data.tableData = res.data.list
      data.total = res.data.total
    }else {
      ElMessage.error("加载失败");
    }
  })
}
load()//初始化数据
const reset = () => {
  data.username = null
  data.userid = null
  load()
}
const toUpdata = (row:any) => {
  data.formVisible = true
  data.form.userid = row.userid
  data.form.role = row.role
  data.form.vip = row.vip
}
const update = () => {
  formRef.value.validate( (valid:any) => {
    if (valid) {
      request.put("/updateUser", data.form).then(res => {
        if (res.status === '200') {
          ElMessage.success("成功");
          data.formVisible = false
          load()
        }else {
          ElMessage.error();
        }
      })
    }
  })
}
const del = (userid:string) => {
  ElMessageBox.confirm("确定删除？","删除操作",{type:"warning"}).then(() => {
    request.delete("/deleteUser/"+userid).then(res => {
      if (res.status == 200) {
        ElMessage.success("删除成功")
        load()
      }else{
        ElMessage.error("删除失败");
      }
    }).catch(() => {})
  })
}
const selectChanges = (rows:any) => {
  data.rows = rows;
  console.log(rows);
}
const delBatch = () => {
  if(data.rows.length === 0){
    ElMessage.warning("请选择要删除的数据")
    return;
  }
  ElMessageBox.confirm("确定删除","批量删除操作",{type:"warning"}).then(() => {
    request.delete("/deleteUsesr",{data:data.rows}).then(res => {
      if (res.status === 200) {
        ElMessage.success("成功")
        load()
      }else{
        ElMessage.error(res.msg);
      }
    })
  }).catch(() => {})
}

//批量导出Excel
const exportExcel = () => {
  // request.get("/export",{//不用这个，他传输的值在request文件里被强制转换为json格式 所以用axious传输数据
  //   params:{
  //     username: data.username,
  //     password: data.password,
  //   },
  //   responseType: 'arraybuffer',
  //   headers: {
  //     "token":data.user.token,
  //   }
  axios.get("http://localhost:8080/export", {
    params: {
      username: data.username,
      password: data.password,
    },
    responseType: 'arraybuffer',
    headers: {
      "token":data.user.token,
    }
  }).then(res => {
    console.log(res)
    downloadExcel(res);
  }).catch(error => {
    ElMessage.error("导出失败");
  })
}
// 得到文件流后，前端生成文件，创建出a标签进行点击
const downloadExcel = function (res:any) {
  if (!res) {
    return;
  }
  const fileName = res.headers["content-disposition"].split("=")[1];
  const blob = new Blob([res.data], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
  });
  const url = window.URL.createObjectURL(blob);
  const aLink = document.createElement("a");
  aLink.style.display = "none";
  aLink.href = url;
  aLink.setAttribute("download", decodeURI(fileName));
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
  window.URL.revokeObjectURL(url);
}
//批量导入Excel
const handleImportSuccess = (res:any) => {
  if (res.status === '200') {
    ElMessage.success('批量导入数据成功')
    load()
  } else {
    ElMessage.error(res.msg)
  }
}

</script>
<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear='load' style="width: 260px; margin-right: 5px" v-model="data.userid" placeholder="请输入账号id查询" prefix-icon="Search"></el-input>
      <el-input clearable @clear='load' style="width: 260px; margin-right: 5px" v-model="data.username" placeholder="请输入用户名查询" prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>

    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="danger" @click="delBatch">批量删除</el-button>
      <el-button type="info" @click="exportExcel">批量导出</el-button>
      <el-upload
          style="display: inline-block; margin-left: 10px"
          action="http://localhost:8080/import"
          :show-file-list="false"
          :on-success="handleImportSuccess"
          :headers="{token: data.user.token}"
      >
        <el-button type="success">批量导入</el-button>
      </el-upload>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData"
                style="width: 100%"
                @selection-change="selectChanges"
                :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }" >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="userid" label="用户id" />
<!--        第一个为遵循的规则名 第二个为列标签名-->
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="password" label="用户密码" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="vip" label="会员" />
        <el-table-column prop="role" label="角色" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
<!--            //数据封装在scope里  将table里的内容打包到了scope里-->
            <el-button type="primary" icon="Edit" @click="toUpdata(scope.row)" circle></el-button>
            <el-button type="danger" icon="Delete" @click="del(scope.row.userid)" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" style="display: flex;flex-direction: column;align-items: center;justify-content: center;">
<!--      分页代码-->
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10]"
          :total="data.total"
          @current-change="load"
          @size-change="load"
      />
    </div>
    <el-dialog  v-model="data.formVisible" width="30%" destroy-on-close>
      <el-form ref="formRef" :model="data.form"  label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="role" label="角色">
          <el-input v-model="data.form.role" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="vip" label="会员">
          <el-input v-model="data.form.vip" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="update">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.card{
  background: rgba(252, 250, 250, 0.82);
}
</style>